package com.example.demo.contoller;

import com.example.demo.config.CommonConstants;
import com.example.demo.model.JsonData;
import com.example.demo.model.VideoDO;
import com.example.demo.vo.UserPointVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 榜单
 */
@RestController
@RequestMapping("/api/rank")
public class RankController {
    /**
     * redis操作对象
     */
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 视频热销日榜单 非实时
     * @return
     */
    @GetMapping("video_daily")
    public JsonData videoRank(){
        List<VideoDO> video = redisTemplate.opsForList().range(CommonConstants.REDIS_DAILY_KEY, 0, -1);
        return JsonData.buildSuccess(video);
    }

    /**
     * 获取有序Set集合，按照分钟从大到小排列
     * @return
     */
    @RequestMapping("get_big")
    public JsonData getZSet(){
        BoundZSetOperations boundZSetOperations = redisTemplate.boundZSetOps("user:point");
        Set set = boundZSetOperations.reverseRange(0, -1);
        return JsonData.buildSuccess(set);
    }

    /**
     * 获取有序Set集合，按照分数从小到大排列
     * @return
     */
    @RequestMapping("get_small")
    public JsonData getZSetSmall(){
        BoundZSetOperations boundZSetOperations = redisTemplate.boundZSetOps("user:point");
        return JsonData.buildSuccess(boundZSetOperations.range(0,-1));
    }

    /**
     * 设置set中成员分数增加
     * @param username
     * @param phone
     * @param score
     * @return
     */
    @RequestMapping("add_score")
    public JsonData setScore( String username, String phone, String score){
        BoundZSetOperations zSet = redisTemplate.boundZSetOps("user:point");
        UserPointVO user = new UserPointVO(username,phone);
        zSet.incrementScore(user, Double.parseDouble(score));
        return JsonData.buildSuccess(zSet.reverseRange(0,-1));
    }

    /**
     * 获取成员分数
     * @param username
     * @param phone
     * @return
     */
    @RequestMapping("get_score")
    public JsonData getScore( String username,String phone){
        BoundZSetOperations zSet = redisTemplate.boundZSetOps("user:point");
        Double score = zSet.score(new UserPointVO(username, phone));
        return JsonData.buildSuccess(score);
    }

    /**
     * 获取成员排名
     * @param username
     * @param phone
     * @return
     */
    @RequestMapping("get_rank")
    public JsonData getRank( String username,String phone){
        Long rank = redisTemplate.boundZSetOps("user:point").rank(new UserPointVO(username, phone));
        return JsonData.buildSuccess(rank);
    }
}
